package com.atguigu.read_write_lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo1 {
    public static void main(String[] args) throws InterruptedException {
        Resource resource = new Resource();

        resource.map.put(1, "value666");

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()->{
                resource.putMap(finalI, "value= " + finalI);
            }, String.valueOf(i)).start();
        }

//        Thread.sleep(1000);

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()->{
                resource.readMap(finalI);
            }, String.valueOf(i)).start();
        }

    }
}

class Resource{
    private int num = 0;
    public Map<Integer, String> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void readNum() {
        readWriteLock.readLock().lock();
        try {
            System.out.println(num);
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void writeNum(int num) {
        readWriteLock.writeLock().lock();
        try{
            this.num = num;
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void readMap(int key) {
        readWriteLock.readLock().lock();
        try {
            String result = map.get(key);
            System.out.println("result = " + result);
        }finally {
            readWriteLock.readLock().unlock();
        }
    }
    public void putMap(int key, String value) {
//        System.out.println("读取map");
        readWriteLock.writeLock().lock();
        try {
            map.put(key, value);
            System.out.println("写入完成");
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }
}